package cn.edu.sjtu.literature.web.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import cn.edu.sjtu.literature.entity.User;
import cn.edu.sjtu.literature.service.exception.UserNotFoundException;
import cn.edu.sjtu.literature.service.exception.UserPasswordInvalidException;
import cn.edu.sjtu.literature.web.util.Constants;
import cn.edu.sjtu.literature.web.view.View;

public class LoginController extends AbstractController {

	@Override
	public View doAction(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		log.debug("do login");
		
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		log.debug("username=" + username);
		req.setAttribute("username", username);
		
		// validate field
		log.debug("validate form");
		boolean hasFieldError = false;
		if (StringUtils.isBlank(username)) {
			req.setAttribute(getFieldErrorKey("username"), "不能为空");
			hasFieldError = true;
		}
		if (StringUtils.isBlank(password)) {
			req.setAttribute(getFieldErrorKey("password"), "不能为空");
			hasFieldError = true;
		}
		log.debug("has field error? " + hasFieldError);
		if (hasFieldError) {
			return getView(Constants.VIEW_LOGIN_FORM);
		}
		
		// login
		log.debug("authenticate user");
		try {
			User user = userService.authenticate(username, password);
			
			// login successfully
			req.getSession().setAttribute(Constants.SESSION_USER_KEY, user);
		
		} catch (UserNotFoundException e) {
			req.setAttribute(Constants.ERROR_MESSAGE_KEY, "用户不存在");
			return getView(Constants.VIEW_LOGIN_FORM);
		} catch (UserPasswordInvalidException e) {
			req.setAttribute(Constants.ERROR_MESSAGE_KEY, "用户名密码不匹配");
			return getView(Constants.VIEW_LOGIN_FORM);
		}
		
		return getRedirectView(req, resp, "homepage");
	}

}
